package com.qbb.server.bean.result;

import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.qbb.server.constanct.FlagAttr;
import com.qbb.server.util.JsonUtil;

/**
 * 类说明
 * 
 * @author chenhuaiao
 * @version V1.0 创建时间：Mar 12, 2015 5:05:18 PM
 */
public class SocketResultBean {
	private String errorMsg;// 结果集生成过程中的异常提示信息
	private Map<String, Object> returnMap = new ConcurrentHashMap<String, Object>();

	public void setResult(Object result) {
		Class clas = this.getClass();
		String simpleName = clas.getSimpleName();
		try {
			if ("SocketResultListMapBean".equals(simpleName)) {
				List<Map<String, Object>> list = (List<Map<String, Object>>) result;
				Method method = clas
						.getDeclaredMethod("setListMap", List.class);
				method.invoke(this, list);
			} else if ("SocketResultMapBean".equals(simpleName)) {
				Map<String, Object> map = (Map<String, Object>) result;
				Method method = clas.getDeclaredMethod("setMap", Map.class);
				method.invoke(this, map);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public String toString() {
		String jsonStr = null;
		try {
			// 存在异常信息的解析方式
			if (errorMsg != null && errorMsg.length() >= 1) {
				returnMap.put(FlagAttr.SUCCESS, FlagAttr.FALSE);
				returnMap.put(FlagAttr.MSG, errorMsg);
				returnMap.remove(FlagAttr.DATA);

				jsonStr = JsonUtil.toJSONString(returnMap);
				return "SocketResultMapBean|" + jsonStr;
			}
			// 没有异常信息的解析处理
			Class clas = this.getClass();
			String simpleName = clas.getSimpleName();
			Method method = null;

			boolean flag = false;
			if ("SocketResultMapBean".equals(simpleName)) {
				method = clas.getDeclaredMethod("getMap");
				Map<String, Object> map = (Map<String, Object>) method
						.invoke(this);
				if (map != null) {
					for (String str : map.keySet()) {
						Object obj = map.get(str);
						if (obj == null) {
							continue;
						}
						returnMap.put(str, obj);
					}
				} else {
					flag = true;
				}
			}
			if (flag) {
				returnMap.put(FlagAttr.SUCCESS, FlagAttr.FALSE);
				returnMap.put(FlagAttr.MSG, "服务接口没有返回Map结果集,Map结果集为空");
				returnMap.remove(FlagAttr.DATA);
			} else {
				if (returnMap.get(FlagAttr.SUCCESS) == null) {
					returnMap.put(FlagAttr.SUCCESS, FlagAttr.TRUE);
				}
				if (returnMap.get(FlagAttr.MSG) == null) {
					returnMap.put(FlagAttr.MSG, "服务接口调用成功");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			returnMap.put(FlagAttr.SUCCESS, FlagAttr.FALSE);
			returnMap.put(FlagAttr.MSG, "服务接口返回数据,存在错误信息!");
			returnMap.remove(FlagAttr.DATA);
		}

		jsonStr = JsonUtil.toJSONString(returnMap);
		return "SocketResultMapBean|" + jsonStr;
	}

	public String getErrorMsg() {
		return errorMsg;
	}

	public void setErrorMsg(String errorMsg) {
		this.errorMsg = errorMsg;
	}

}
